package net;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Stream工具类
 */
public class StreamUtils {

    /**
     * 功能： 将输入流转换成byte[]，即可以把文件的内容读入到byte[]
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] streamToByteArray(InputStream inputStream) throws Exception {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; //字节数组
        int length;
        while ((length = inputStream.read(buffer)) != -1) { //循环读取
            byteArrayOutputStream.write(buffer, 0, length); //把读取到的数据，写入到字节数组
        }
        byte[] array = byteArrayOutputStream.toByteArray(); //然后将 byteArrayOutputStream 转成字节数组
        byteArrayOutputStream.close();
        return array;
    }

    /**
     * 功能：将InputStream转换成String
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String streamToString(InputStream inputStream) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {    //当读取到null时，表示读取完毕
            stringBuilder.append(line + "\r\n");
        }
        return stringBuilder.toString();
    }
}
